import React, { PureComponent, Fragment } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Select, Spin, Input, Button, Card, message, Divider, Modal, AutoComplete } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import router from 'umi/router';
import DictCode from '../components/DictCode';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = AutoComplete;
const { Description } = DescriptionList;
const { confirm } = Modal;
const { TextArea } = Input;
const FormItem = Form.Item;
@connect(({ searchrecord, loading }) => ({
  searchrecord,
  loading: loading.models.searchrecord,
}))
@Form.create()
class AddSearchRecord extends PureComponent {
  componentDidMount() {
    const { dispatch, location } = this.props;
    const { rcrdId } = location.query;
    if (rcrdId) {
      dispatch({
        type: 'searchrecord/getDic',
        payload: ['MSGTYPE', 'CONSULT_WAY', 'CONSULT_STATUS'],
      }).then(() => {
        this.detail(rcrdId);
      });
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const parmters = {
      replyContent: undefined,
      remindDate: undefined,
      state: '2',
      content: undefined,
      type: undefined,
      consultWay: undefined,
      othContactWay: undefined,
      contactEmail: undefined,
      contactPhone: undefined,
      areaName: undefined,
      custName: undefined,
      certNo: undefined,
      empName: undefined,
      rcrdId: undefined,
      vno: undefined,
      historyArr: [],
    };
    dispatch({
      type: 'searchrecord/updateModelData',
      payload: parmters,
    });
  }

  // 查看接口
  detail = rcrdId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'searchrecord/fetchDetail',
      payload: { rcrdId },
    });
  };

  // 改变状态
  stateOnChange = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'searchrecord/updateModelData',
      payload: { state: e.target.value },
    });
  };

  // 搜索
  search = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      const values = {
        empName: value.trim(),
      };
      dispatch({
        type: 'searchrecord/fetchEmpNameList',
        payload: values,
      });
    }
  };

  // 搜索证件号
  searchCert = () => {
    const {
      form: { validateFieldsAndScroll },
      form,
      dispatch,
    } = this.props;
    validateFieldsAndScroll(['certNo'], (err, values) => {
      if (!err) {
        dispatch({
          type: 'searchrecord/fetchEmpNameList',
          payload: values,
        }).then(response => {
          if (!response.data.length) {
            form.setFieldsValue({
              empName: undefined,
              certNo: undefined,
              custName: undefined,
              areaName: undefined,
              contactPhone: undefined,
              contactEmail: undefined,
            });
          }
        });
      }
    });
  };

  // 选择姓名
  empData = value => {
    const {
      searchrecord: { empNameList },
    } = this.props;
    if (empNameList) {
      empNameList.map(item => {
        if (item.sendId === value) {
          this.valueBase(item);
        }
        return true;
      });
    }
  };

  // 校验证件号
  valueBase = item => {
    const { form } = this.props;
    this.setState({
      empName: item.empName,
    });
    Object.keys(item).forEach(key => {
      if (
        key === 'areaId' ||
        key === 'custId' ||
        key === 'empId' ||
        key === 'certNo' ||
        key === 'certType'
      ) {
        this.setState({
          [key]: item[key],
        });
      }
    });
    form.resetFields();
    form.setFieldsValue({
      empName: item.empName,
      certNo: item.certNo,
      custName: item.custName,
      areaName: item.areaName,
      contactPhone: item.contactPhone,
      contactEmail: item.contactEmail,
    });
  };

  // 保存
  save = () => {
    const { form, dispatch, searchrecord } = this.props;
    const getFieldsList = form.getFieldsValue();
    const arr = [];
    Object.entries(getFieldsList).forEach(([key]) => {
      arr.push(key);
    });
    form.validateFieldsAndScroll(
      searchrecord.rcrdId
        ? ['consultWay', 'type', 'content', 'state', 'replyContent', 'remindDate', 'othContactWay']
        : arr,
      (err, values) => {
        const newValue = values;
        newValue.remindDate = values.remindDate ? values.remindDate.format('YYYY-MM-DD') : null;
        newValue.type = values.type && values.type.join(',');
        if (!err) {
          if (searchrecord.rcrdId) {
            dispatch({
              type: 'searchrecord/updateDataList',
              payload: { ...newValue },
              callback: res => {
                if (res.success) {
                  router.goBack();
                }
              },
            });
          } else {
            const { areaId, custId, empId, empName, certType } = this.state;
            newValue.empCorpName = newValue.custName;
            newValue.empName = empName;
            newValue.empCorpId = custId;
            newValue.certType = certType;
            delete newValue.custName;
            dispatch({
              type: 'searchrecord/addCheckList',
              payload: { ...newValue, areaId, empId },
              callback: response => {
                if (response) {
                  if (response.data.code === '201') {
                    message.error('该姓名已存在，不可以新增！');
                  } else if (response.data.code === '202') {
                    confirm({
                      title: '提醒',
                      content: '当前人员已存在此项服务，是否确定重复添加?',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      onOk: () => {
                        dispatch({
                          type: 'searchrecord/addList',
                          payload: { ...newValue, areaId, custId, empId },
                          callback: res => {
                            if (res.success) {
                              router.goBack();
                            }
                          },
                        });
                      },
                      onCancel() {},
                    });
                  } else if (response.data.code === '200') {
                    router.goBack();
                  }
                }
              },
            });
          }
        }
      }
    );
  };

  // 取消
  cancle = () => {
    const { searchrecord } = this.props;
    confirm({
      title: searchrecord.rcrdId ? '确定要取消更新吗?' : '确定要取消保存吗?',
      content: searchrecord.rcrdId
        ? '取消更新后原记录不做更新?'
        : '取消保存后将看不到此条新增记录?',
      okText: '离开',
      cancelText: '取消',
      onOk() {
        router.goBack();
      },
      onCancel() {},
    });
  };

  // 证件号校验
  idVailFunc = () => {
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll(['certNo'], (err, values) => {
      if (!err) {
        if (values) {
          dispatch({
            type: 'searchrecord/fetchEmpNameList',
            payload: values,
          }).then(resp => {
            if (resp.success) {
              if (resp.data && resp.data.length === 0) {
                message.warning('当前所输的证件号不存在，请检查 ');
                form.resetFields([
                  'empName',
                  'custName',
                  'areaName',
                  'contactPhone',
                  'contactEmail',
                ]);
              } else {
                const certObj = resp.data[0];
                this.valueBase(certObj);
              }
            } else {
              message.error(resp.message || '服务器错误');
            }
          });
        }
      }
    });
  };

  render() {
    const { form, searchrecord, loading } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 8,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 10,
        },
      },
    };
    let options = null;
    if (searchrecord.empNameList && searchrecord.empNameList.length) {
      options = searchrecord.empNameList.map(opt => (
        <Option key={opt.sendId}>{`${opt.certNo} (${opt.custName})`}</Option>
      ));
    }
    return (
      <PageHeaderWrapper>
        <Spin spinning={loading} size="large">
          <Card title={<span>{searchrecord.rcrdId ? '更新咨询记录' : '新增咨询记录'}</span>}>
            <Form>
              <FormItem {...formItemLayout} label={<span>姓名 </span>}>
                {getFieldDecorator('empName', {
                  rules: [
                    {
                      required: !searchrecord.rcrdId,
                      message: '只能输入汉字或者英文',
                    },
                  ],
                })(
                  searchrecord.rcrdId ? (
                    <span>{searchrecord.empName}</span>
                  ) : (
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      style={{ width: '100%' }}
                      showSearch
                      optionFilterProp="children"
                      showArrow={false}
                      onSearch={this.search}
                      onSelect={this.empData}
                      notFoundContent={loading ? <Spin size="small" /> : '暂无数据'}
                    >
                      {searchrecord.empNameList.length &&
                        searchrecord.empNameList.map(item => (
                          <Option key={item.sendId}>{`${item.empName}(${item.custName})`}</Option>
                        ))}
                    </HOCSelect>
                  )
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="证件号:">
                {getFieldDecorator('certNo', {
                  rules: [
                    {
                      required: !searchrecord.rcrdId,
                      message: '请输入证件号',
                    },
                  ],
                })(
                  searchrecord.rcrdId ? (
                    <span>{searchrecord.certNo}</span>
                  ) : (
                    <AutoComplete
                      dropdownMatchSelectWidth={false}
                      // style={{ width: '96%' }}
                      dataSource={options}
                      placeholder="请输入证件号"
                      onSelect={this.empData}
                    >
                      <Input suffix={<SearchOutlined onClick={this.searchCert} />} />
                    </AutoComplete>
                  )
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={<span>客户名称</span>}>
                {getFieldDecorator('custName', {
                  rules: [
                    {
                      required: !searchrecord.rcrdId,
                      message: '请填写客户名称',
                    },
                  ],
                })(
                  searchrecord.rcrdId ? (
                    <span>{searchrecord.empCorpName || '--'}</span>
                  ) : (
                    <Input placeholder="请填写客户名称" disabled />
                  )
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={<span>执行地</span>}>
                {getFieldDecorator('areaName', {
                  rules: [
                    {
                      required: !searchrecord.rcrdId,
                      message: '请填写执行地',
                    },
                  ],
                })(
                  searchrecord.rcrdId ? (
                    <span>{searchrecord.areaName || '--'}</span>
                  ) : (
                    <Input placeholder="请填写执行地" disabled />
                  )
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={<span>电话</span>}>
                {getFieldDecorator('contactPhone', {
                  rules: [
                    {
                      required: false,
                      message: '请正确输入手机号码或固话(限制12位)',
                      pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                    },
                  ],
                })(
                  searchrecord.rcrdId ? (
                    <span>{searchrecord.contactPhone || '--'}</span>
                  ) : (
                    <Input placeholder="请填写电话" />
                  )
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={<span>邮箱</span>}>
                {getFieldDecorator('contactEmail', {
                  rules: [
                    {
                      type: 'email',
                      message: '输入的电子邮件无效!',
                    },
                    {
                      required: false,
                      message: '请填写邮箱！',
                    },
                  ],
                })(
                  searchrecord.rcrdId ? (
                    <span>{searchrecord.contactEmail || '--'}</span>
                  ) : (
                    <Input placeholder="请填写邮箱" />
                  )
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={<span>咨询方式</span>}>
                {getFieldDecorator('consultWay', {
                  rules: [
                    {
                      required: true,
                      message: '请填写咨询方式',
                    },
                  ],
                  initialValue: searchrecord.consultWay && `${searchrecord.consultWay}`,
                })(<DictCode dictType="CONSULT_WAY" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="咨询类型">
                {getFieldDecorator('type', {
                  rules: [
                    {
                      required: true,
                      message: '请填写咨询类型',
                    },
                  ],
                  initialValue: searchrecord.type && searchrecord.type.split(','),
                })(<DictCode dictType="MSGTYPE" mode="multiple" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="咨询内容">
                {getFieldDecorator('content', {
                  rules: [
                    {
                      required: true,
                      message: '请填写咨询内容',
                    },
                  ],
                  initialValue: searchrecord.content,
                })(<TextArea placeholder="请填写咨询内容" />)}
              </FormItem>
              <Divider />
              <FormItem {...formItemLayout} label="回复状态">
                {getFieldDecorator('state', {
                  rules: [
                    {
                      required: true,
                      message: '请选择回复状态',
                    },
                  ],
                  initialValue: `${searchrecord.state}`,
                })(
                  <DictCode dictType="CONSULT_STATUS" inputType="3" onChange={this.stateOnChange} />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="回复内容">
                {getFieldDecorator('replyContent', {
                  rules: [
                    {
                      required: true,
                      message: '请输入不超过100个字的回复内容',
                      max: 100,
                    },
                  ],
                  initialValue: searchrecord.replyContent,
                })(<TextArea placeholder="请输入回复内容" />)}
              </FormItem>
            </Form>
          </Card>
          {searchrecord.rcrdId && (
            <Card title="历史记录">
              {!!searchrecord.historyArr.length &&
                searchrecord.historyArr.map((item, i) => (
                  <Fragment>
                    <DescriptionList>
                      <Description term="更新人员">{item.operName || '--'}</Description>
                      <Description term="更新时间">
                        {item.operTime ? moment(item.operTime).format('YYYY-MM-DD HH:mm') : '--'}
                      </Description>
                      <Description term="回复状态">{item.stateName || '--'}</Description>
                      <Description term="咨询方式">{item.consultWayName || '--'}</Description>
                      <Description term="咨询类型">{item.typeName || '--'}</Description>
                      <Description term="咨询内容">{item.content || '--'}</Description>
                      <Description term="回复内容">{item.replyContent || '--'}</Description>
                    </DescriptionList>
                    {searchrecord.historyArr.length === i + 1 ? null : <Divider dashed />}{' '}
                  </Fragment>
                ))}
              {!searchrecord.historyArr.length && '暂无数据'}
            </Card>
          )}
        </Spin>

        <FooterToolbar style={{ width: '100%' }}>
          <Button onClick={this.cancle}>取消</Button>
          <Button type="primary" onClick={this.save}>
            保存
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}
export default AddSearchRecord;
